

package jumavidesktop.configuracion;

import java.util.HashMap;
import java.util.Map;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import jumavidesktop.Otros.Pojos.parConfig;

/**
 *
 * @author vimso
 */

public class Configuracion {
    
    private static Configuracion Instance ;    
   public static Configuracion getInstance()
   {
       if(Instance==null)
       {
           Instance= new Configuracion();
       }
       return Instance;
   }
   
   //<editor-fold defaultstate="collapsed" desc="Métodos">  
   
   public void cargarConfiguracion(parConfig parametros)
   {
       this.setParametros(parametros);
        this.setEntityManager(this.cargarEntityManager(parametros));
   }
         
    private EntityManager cargarEntityManager(parConfig parametros)
    {
        //Creo la unidad de persistencia en tiempo de ejecución.
        Map<String, String> dbProps = new HashMap<String, String>();

        dbProps.put("javax.persistence.jdbc.url",
                parametros.getUrlBBDD());
        dbProps.put("javax.persistence.jdbc.password",
                parametros.getClave());
        dbProps.put("javax.persistence.jdbc.drive",
               "com.mysql.jdbc.Driver");
        dbProps.put("javax.persistence.jdbc.user",
                parametros.getUsuario());
        this.setEntityManagerFactory(Persistence.createEntityManagerFactory("JumaviDesktopPU", dbProps));
        EntityManager em= this.getEntityManagerFactory().createEntityManager(); //Establezco un entitymanager por defecto
        return em;
    }
           
           //</editor-fold>
   //<editor-fold defaultstate="collapsed" desc="Atributos">
    private EntityManagerFactory entityManagerFactory; 
   private EntityManager entityManager;
   private parConfig parametros;
   //</editor-fold>
   //<editor-fold defaultstate="collapsed" desc="Setter y getter">

    public EntityManagerFactory getEntityManagerFactory() {
        return entityManagerFactory;
    }

    private void setEntityManagerFactory(EntityManagerFactory entityManagerFactory) {
        this.entityManagerFactory = entityManagerFactory;
    }
   
    public EntityManager getNewEntityManager() {
        return this.getEntityManagerFactory().createEntityManager(); 
    }
   
    public EntityManager getEntityManager() {
        return entityManager;
    }

    public void setEntityManager(EntityManager entityManager) {
        this.entityManager = entityManager;
    }
    
    public parConfig getParametros() {
        return parametros;
    }

    public void setParametros(parConfig parametros) {
        this.parametros = parametros;
    }
    
    public void desconectarBBDD()
    {
        this.entityManagerFactory.close();
    }
    //</editor-fold>
}
